jclass={
    initPage:function(){
        // 绑定dom对象
        this.obj = {
            searchText:$('#searchText'),
        };
        this.weeks = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
        // 声明全局变量
        this.data = {
            datatable:[],
            tableParams: {
                page:1,
                size:10
            },
            addcgParams: {
                objectId:'',
                objectType: '0',
                platformId: '',
                platformName: '',
                owersId: '',
                owersName: '',
                JobType: '3',
                time: '',
                dayOfWeeks: '1',
                informationId: '',
                checkInformation: ''
            },
            dialogZqSelectedArr:[1],
            selectTypeArr:[{val:'0',name:'全部'},{val:'1',name:'当前连接下级平台'},{val:'2',name:'下级平台所属的单一业户'}],  
            selectCgxxArr:[]
    
        };
        this.getTableList();
        // this.creatTable({data:{},total:0});
        this.init();
        this.bindEvent();
        
    },
    init() {
        let that = this

        //选择时分秒
        $('.J-datepicker-time').datePicker({
          format: 'HH:mm:ss',
          hide: function (type) {
                // console.info(this.$input.val());
                that.data.addcgParams.time = this.$input.val()
            }
        });

        // 重置
        $("#resetClick").click(() => {
            $("#input_informationProblem").val('')
            this.data.tableParams = {
                page:1,
                size:10
            }
        })

        // 查询
        $("#searchClick").click(() => {
            this.getTableList()
        })

        jrequest.get("/api/command-problem",{}).then(res => {
            // let options = ''
            // res.data.forEach(item => {
            //     options += `<option value=${item.id}>${item.informationProblem}</option>`
            // })
            // $("#cgin_select").html(options)
            res.data.forEach(item => {
                item.val = item.id
                item.name = item.informationProblem
            })
            this.data.selectCgxxArr = res.data
            jdSelect.JdSelectRadioInit('#d_select_cgxx',res.data,(select) => {
                // console.log(select)
                this.data.addcgParams.informationId = select.val
                this.data.addcgParams.checkInformation = select.name
            })
        })

        jdSelect.JdSelectRadioInit('#d-select-duix',this.data.selectTypeArr,(select) => {
                // {name:'',val:''}
                let selectedVal = select.val + ''
                this.data.addcgParams.objectType = selectedVal
                if (selectedVal === "0") {
                    $("#dialogUser").hide()
                    $("#dialog_platform").hide()
                    $(".dialog-s-center-h").height(170)
                }if (selectedVal === "1") {
                    $("#dialogUser").hide()
                    $("#dialog_platform").show()
                    $(".dialog-s-center-h").height(220)
                }else if(selectedVal === "2"){
                    $("#dialogUser").show()
                    $("#dialog_platform").show()
                    $(".dialog-s-center-h").height(270)
                }

                that.autoInputFun("#dPlatformInput", "#dplatformListUl", 
                    "/api/assessMent/selectPlatformAll", {}, "platformName", res => {
                        if (res) {
                            let html = ''
                            res.forEach(item => {
                                html += `<li onclick="dPlatformSelect(this)" 
                                    data-platformcode=${item.platformCode}
                                    data-platformid=${item.id}
                                    data-areaid=${item.areaId}
                                    data-item="${item.name}">${item.name}</li>`
                            })
                            $("#dplatformListUl").html(html)
                        }
                    })
            })

    },

    // 自动 input下list框
    autoInputFun(inputId,ulId,url,params,name,callback) {
        $(inputId).bind("input propertychange",function(event){
            params = params || {}
            let inputval = $(inputId).val()
            params[name] = inputval
            if (inputval) {
                $(ulId).show()
                jrequest.get(url,params).then(res => {
                    if (res.data.length) {
                        callback(res.data);
                    } else {
                        html = '<li style="text-align:center;">暂无数据</li>'
                        $(ulId).html(html)
                        callback(null)
                    }
                })
            } else {
                $(ulId).hide()
                $(ulId).html('')
            }
        });
    },
    bindEvent() {
        let that = this
        $("#dialogUser").hide()
        $("#dialog_platform").hide()
        // $("#objectSelect").change(function() {
        //     let selectedVal = $("#objectSelect option:selected").val()
        //     if (selectedVal === "0") {
        //         $("#dialogUser").hide()
        //         $("#dialog_platform").hide()
        //         $(".dialog-s-center-h").height(170)
        //     }if (selectedVal === "1") {
        //         $("#dialogUser").hide()
        //         $("#dialog_platform").show()
        //         $(".dialog-s-center-h").height(220)
        //     }else if(selectedVal === "2"){
        //         $("#dialogUser").show()
        //         $("#dialog_platform").show()
        //         $(".dialog-s-center-h").height(270)
        //     }

        //     that.autoInputFun("#dPlatformInput", "#dplatformListUl", 
        //         "/api/assessMent/selectPlatformAll", {}, "platformName", res => {
        //             if (res) {
        //                 let html = ''
        //                 res.forEach(item => {
        //                     html += `<li onclick="dPlatformSelect(this)" 
        //                         data-platformcode=${item.platformCode}
        //                         data-platformid=${item.id}
        //                         data-areaid=${item.areaId}
        //                         data-item="${item.name}">${item.name}</li>`
        //                 })
        //                 $("#dplatformListUl").html(html)
        //             }
        //         })
        // })

        $("#add_btn_cg").click(() => {
            if (!$("#d_select_zhouqi").text()) {
                JPop.alert({msg:'请选择一个查岗周期'})
                // Jdialog.alert("请选择一个查岗周期")
                return false
            } else {
                let dataform = $("#form_autocg").serializeArray()
                let a = true
                console.log(dataform)
                dataform.forEach(item => {
                    if(!item.value) a=false
                })
                if(a) {
                    // this.data.addcgParams.objectType = $("#objectSelect option:selected").val()
                    let days = ''
                    this.data.dialogZqSelectedArr.forEach(item => {
                        days += `${item},`
                    })
                    this.data.addcgParams.dayOfWeeks = days.slice(0,-1)
                    // this.data.addcgParams.informationId = $("#cgin_select option:selected").val()
                    // this.data.addcgParams.checkInformation = $("#cgin_select option:selected").text()
                    if($("#jdialog_title").text() === '编辑') {
                        jrequest.put("/api/automatic_check_setting",this.data.addcgParams).then(res => {
                            if (res.data.code === '1') {
                                JPop.alert({msg:'修改成功！',type:'success'})
                                closeDialog()
                                this.getTableList()
                            }
                        })
                    } else {
                        this.data.addcgParams.id = ''
                        jrequest.post("/api/automatic_check_setting",this.data.addcgParams).then(res => {
                            if (res.data.code === '1') {
                                JPop.alert({msg:'添加成功！',type:'success'})
                                closeDialog()
                                this.getTableList()
                            }
                        })
                    }
                    return false
                }
            }

            
        })

        $("#d_select_zhouqi").click(() => {
            $("#d_select_ul_zq").toggle()
        })

        $("#d_select_ul_zq li").click(function() {
            // console.log($(this).hasClass("active"))
            let namestr = ''
            if ($(this).hasClass("active")) {
                $(this).removeClass("active").find("span").removeClass("active")
                $(this).find("span").hide()
                console.log(that.data.dialogZqSelectedArr.indexOf($(this).data("val")))
                that.data.dialogZqSelectedArr.splice(that.data.dialogZqSelectedArr.indexOf($(this).data("val")),1)
            } else {
                $(this).addClass("active").find("span").addClass("active")
                $(this).find("span").show()
                that.data.dialogZqSelectedArr.push($(this).data("val"))
            }
            that.data.dialogZqSelectedArr.forEach(item => {
                namestr += `${that.weeks[Number(item)-1]},`
            })
            $("#d_select_zhouqi").text(namestr)
            // console.log(that.data.dialogZqSelectedArr)
            
        })

        $(document).click(function (event) {
            var x1 = $('#dselect_zq_div'); // 设置目标区域
            // console.log(event)
            if (!x1.is(event.target) && x1.has(event.target).length === 0) {
                // $("#jnotic_user").hide()
                $("#d_select_ul_zq").hide()
            }
        })

    },
    getTableList() {
        this.data.tableParams.informationProblem = $("#input_informationProblem").val()
        jrequest.get("/api/automatic_check_setting",this.data.tableParams).then(res => {
            res.data.forEach(item => {
                if (item.dayOfWeeks) {
                    let arr = item.dayOfWeeks.split(",")
                    let str = ''
                    arr.forEach(week => {
                        str += `${this.weeks[Number(week)-1]},`
                    })
                    item.dayOfWeeksName = str.slice(0,-1)
                }
                
            })
            this.data.datatable = res.data
            // $("#jtable_autocgang").bootstrapTable('load',res.data);
            $("#jtable_autocgang").bootstrapTable('destroy');
            this.creatTable(res)
        })
    },
    creatTable:function(res){
        var self=this;
        var columnsOne = [
            {
                title : '序号',
                align: "center",
                formatter: function (value, row, index) {
                    //获取每页显示的数量
                    var pageSize=self.data.tableParams.size;
                    //获取当前是第几页
                    var pageNumber=self.data.tableParams.page;
                    //返回序号，注意index是从0开始的，所以要加上1
                    return pageSize * (pageNumber - 1) + index + 1;
                }
            },
            {
              field: "objectId",
              title: "查岗对象类型"
            },
            {
              field: "objectType",
              title: "查岗对象"
            },
            {
              field: "dayOfWeeksName",
              title: "查岗周期"
            },
            {
              field: "time",
              title: "查岗时间"
            },
            {
              field: "checkInformation",
              title: "查岗信息"
            },
            {
              field: "isSwitch",
              title: "查岗状态"
            },
            {
              field: "founder",
              title: "创建人"
            },
            {
              field: "createTime",
              title: "创建时间"
            },
            {
                field: 'Button',
                title: '操作',
                width: "200",
                align: 'center',
                events: operateEvents,
            }
        ];
        self.tableEvent("jtable_autocgang",res.data,columnsOne,true,res.total);
    },
    tableEvent:function(id,data,columns,paginationShow,total){
        data.forEach(item => {
            item.Button = this.operateFormatter(item.isSwitch)
        })
        let that = this
        $('#' + id).bootstrapTable({
            method: 'get',
            cache: false,
            height: 320,
            pagination: paginationShow,
            pageSize: that.data.tableParams.size,
            pageNumber:that.data.tableParams.page,
            striped: true,
            columns: columns,
            sidePagination: 'server', // client or server
            totalRows: total,
            data :data,
            onPageChange: function (size, number) {
                console.log(number)
                that.data.tableParams.page = number
                that.data.tableParams.size = size
                that.getTableList()
            },
            formatNoMatches: function(){
                return '暂无数据';
            }
        });
    },
    operateFormatter(isSwitch) {
        if (isSwitch == 0) { // 开启状态
            return [
                '<button type="button" id="table_edit">修改</button>',
                '<button type="button" id="table_close">关闭</button>'
            ].join('');
        } else { // 关闭状态
            return [
                '<button type="button" id="table_edit">修改</button>',
                '<button type="button" id="table_close">开启</button>'
            ].join('');
        }
    }
    
}

$(function(){
    jclass.initPage();

    // 表格操作按钮
    window.operateEvents = {
        'click #table_close': (e,value,row,index) => {
            // console.log(row)
            let msg = ''
            if (row.isSwitch == 0) {
                msg = "确定要关闭自动查岗设置？"
            } else {
                msg = "确定要开启自动查岗设置？"
            }
            // Jdialog.confirm({ message: msg }).on(function (e) {
            //     if (e) {
            //         // console.log(row.id)
            //         let isSwitch = 0
            //         if (row.isSwitch == 0) {
            //             isSwitch = 1
            //         } else {
            //             isSwitch = 0
            //         }
            //         jrequest.put(`/api/automatic_check_setting`,{id:row.id,isSwitch:isSwitch}).then(res => {
            //             if (res) {
            //                 jclass.getTableList()
            //             }
            //         })
            //     }
            // });
            JPop.dialogDel({msg:msg,operate:true}).on(success => {
                if (success) {
                    // console.log(row.id)
                    let isSwitch = 0
                    if (row.isSwitch == 0) {
                        isSwitch = 1
                    } else {
                        isSwitch = 0
                    }
                    jrequest.put(`/api/automatic_check_setting`,{id:row.id,isSwitch:isSwitch}).then(res => {
                        if (res) {
                            jclass.getTableList()
                        }
                    })
                }
            })
        },
        'click #table_edit': (e,value,row,index) => {
            // console.log(row)
            jclass.data.addcgParams.objectId = row.objectId
            jclass.data.addcgParams.objectType = row.objectType
            // $("#objectSelect").find(`option[value=${row.objectType}]`).attr("selected",true)
            jdSelect.setSelectRadio("#d-select-duix",jclass.data.selectTypeArr,row.objectType)
            jclass.data.addcgParams.informationId = row.informationId
            // $("#cgin_select").find(`option[value=${row.informationId}]`).attr("selected",true)
            jdSelect.setSelectRadio("#d_select_cgxx",jclass.data.selectCgxxArr,row.informationId)
            jclass.data.addcgParams.checkInformation = row.checkInformation
            // let time = moment(row.time).format("HH:mm:ss")
            // $("#d_input_cgtime").val(time)
            $("#d_input_cgtime").val(row.time)
            jclass.data.addcgParams.dayOfWeeks = row.dayOfWeeks
            let weekarr = row.dayOfWeeks.split(",")
            let arr = []
            weekarr.forEach(item => {
                arr.push(parseInt(item))
            })
            jclass.data.dialogZqSelectedArr = arr
            console.log(jclass.data.dialogZqSelectedArr)
            $("#d_select_zhouqi").text(row.dayOfWeeksName)

            $("#d_select_ul_zq li").each(function(i,dom){
                weekarr.forEach(week => {
                    if($(dom).data("val") == week){
                        $(dom).addClass("active")
                        $(dom).find("span").addClass("active")
                    }
                })
                
            })

            jclass.data.addcgParams.id = row.id

            if (row.objectType === "0") {
                $("#dialogUser").hide()
                $("#dialog_platform").hide()
                $(".dialog-s-center-h").height(170)
            }if (row.objectType === "1") {
                $("#dialogUser").hide()
                $("#dialog_platform").show()
                $(".dialog-s-center-h").height(220)
            }else if(row.objectType === "2"){
                $("#dialogUser").show()
                $("#dialog_platform").show()
                $(".dialog-s-center-h").height(270)
            }

            jclass.data.addcgParams.platformId = row.platformId
            jclass.data.addcgParams.platformName = row.platformName
            jclass.data.addcgParams.owersId = row.owersId
            jclass.data.addcgParams.owersName = row.owersName
            $("#dPlatformInput").val(row.platformName)
            $("#dUserInput").val(row.owersName)



            openDialog("edit")
        }
    }
});

function openDialog(type) {
    type = type || ''
    if (type === 'edit') {
        $("#jdialog_title").text("编辑")
    } else {
        $("#jdialog_title").text("添加")
    }
    $("#autocgDialog").show()
    $("#d_select_ul_zq li").eq(0).addClass("active")
    $("#d_select_ul_zq li").eq(0).find("span").addClass("active")

}
function closeDialog() {
    $("#dialog_platform").val('')
    $("#dialog_platform").hide()
    $("#dialogUser").val('')
    $("#dialogUser").hide()
    $(".dialog-s-center-h").height(170)

    $("#dPlatformInput").val('')
    $("#dUserInput").val('')
    $("#d_input_cgtime").val('')

    // $("#objectSelect").find("option[value='0']").attr("selected",true)
    jdSelect.resetSelectRadio("#d-select-duix",jclass.data.selectTypeArr[0].name)
    jdSelect.resetSelectRadio("#d_select_cgxx",jclass.data.selectCgxxArr[0].name)

    jclass.data.dialogZqSelectedArr = [1]
    $("#d_select_zhouqi").text("星期一")
    $("#d_select_ul_zq").hide()
    $.each($('#d_select_ul_zq li'),function(i,ele) {
        $(ele).removeClass("active").find("span").removeClass("active")
    })

    $("#autocgDialog").hide()
}

function dPlatformSelect(obj) {
    $("#dPlatformInput").val($(obj).data("item"))
    jclass.data.addcgParams.platformName = $(obj).data("item")
    jclass.data.addcgParams.platformId = $(obj).data("platformid")
    jclass.data.addcgParams.objectId = `${$(obj).data("platformcode")}${$(obj).data("areaid")}`

    $("#dplatformListUl").hide()
    $("#dplatformListUl").html('')

    // 选择平台id 查询业户
    jclass.autoInputFun("#dUserInput", "#dUserListUl", 
        "/api/owsers/listOwers", {platformId:jclass.data.addcgParams.platformId}, "owersName", res => {
            if (res) {
                let html = ''
                res.forEach(item => {
                    html += `<li onclick="dUserSelect(this)"
                        data-owersid=${item.id}
                        data-rtoln=${item.rtoln}
                        data-item="${item.owersName}">${item.owersName}</li>`
                })
                $("#dUserListUl").html(html)
            }
        })
}
function dUserSelect(obj) {
    $("#dUserInput").val($(obj).data("item"))
    jclass.data.addcgParams.owersId = $(obj).data("owersid")
    jclass.data.addcgParams.owersName = $(obj).data("item")
    jclass.data.addcgParams.objectId = $(obj).data("rtoln")

    $("#dUserListUl").hide()
    $("#dUserListUl").html('')
}

